package com.whmskj.xjlhbc.service.impl;

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.PatternPool;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhbc.domain.*;
import com.whmskj.xjlhbc.dto.EquipmentGroupDTO;
import com.whmskj.xjlhbc.dto.JtQueryDto;
import com.whmskj.xjlhbc.dto.ZjktQueryDto;
import com.whmskj.xjlhbc.mapper.*;
import com.whmskj.xjlhbc.service.*;
import com.whmskj.xjlhbc.vo.GzTjVo;
import com.whmskj.xjlhbc.vo.GzinfoRecordVo;
import com.whmskj.xjlhbc.vo.WbInfoRecordVo;
import com.whmskj.xjlhbc.vo.WbTjVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class Sb11dknittingstationstiedServiceImpl
        extends ServiceImpl<Sb11dknittingstationstiedMapper, Sb11dknittingstationstied> implements ISb11dknittingstationstiedService {

    @Autowired
    private Sc13dWrotePlannerTableMapper sc13dWrotePlannerTableMapper;

    @Autowired
    private By01MaintenanceScheduleMapper by01MaintenanceScheduleMapper;

    @Autowired
    private SchedulingOfSbbx01MalfunctionRepMapper schedulingOfSbbx01MalfunctionRepMapper;

    @Autowired
    private CorpMemberMapper corpMemberMapper;

    @Autowired
    private ISublistOfDailyAttendanceRecordsFService sublistOfDailyAttendanceRecordsFService;

    @Autowired
    private ThePlanesStrappedToATableMapper thePlanesStrappedToATableMapper;

    @Autowired
    private IPersonnelManagementDataSheetsService personnelManagementDataSheetsService;

    @Autowired
    private ReplaceAccessoriesService replaceAccessoriesService;

    @Autowired
    private PersonnelManagementDataSheetsMapper personnelManagementDataSheetsMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private ReplaceAccessoriesMapper replaceAccessoriesMapper;

    @Autowired
    private IRundataInfoService rundataInfoService;

    @Override
    public List<Sb11dknittingstationstied> queryList(String id, String date) {
        String d = StringUtils.hasText(date) ? date : LocalDate.now().toString();
        List<String> jtList = new ArrayList<>();
        String classesInTheClassroom;
        if(StringUtils.hasText(id)){
            SublistOfDailyAttendanceRecordsF sublistOfDailyAttendanceRecordsF = sublistOfDailyAttendanceRecordsFService.getById(id);
            classesInTheClassroom = sublistOfDailyAttendanceRecordsF.getClassesInTheClassroom();
            LambdaQueryWrapper<ThePlanesStrappedToATable> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ThePlanesStrappedToATable::getNameOfPersonnel, sublistOfDailyAttendanceRecordsF.getNameOfEmployee());
            wrapper.eq(ThePlanesStrappedToATable::getF7ba, d);
            wrapper.last("limit 1");
            ThePlanesStrappedToATable thePlanesStrappedToATable = Optional.ofNullable(thePlanesStrappedToATableMapper.selectOne(wrapper)).orElseGet(ThePlanesStrappedToATable::new);
            if(StringUtils.hasText(thePlanesStrappedToATable.getF657()))
                jtList.addAll(Arrays.stream(thePlanesStrappedToATable.getF657().split(",")).collect(Collectors.toList()));
        } else {
            classesInTheClassroom = null;
        }
        List<Sb11dknittingstationstied> list = baseMapper.queryList();
        list.forEach(item->{
            String wroteboardStationNumber = item.getWroteboardStationNumber();
            List<Map<String, Object>> jthList = baseMapper.selectJtList(wroteboardStationNumber, d,classesInTheClassroom);
            jthList.forEach(jt->{
                String jth = jt.get("wroteSequenceNumber").toString();
                if(jtList.contains(jth)){
                    jt.put("hasBind", 0);
                }
            });
            item.setJthList(jthList);
        });
        return list;
    }

    @Override
    public List<Sc13dWrotePlannerTable> zjktList(ZjktQueryDto param) {
        List<Sc13dWrotePlannerTable> list = sc13dWrotePlannerTableMapper.zjktList(LocalDate.now().toString());
        String loomstate = param.getLoomstate();
        int xl = param.getXl();
        int lb = param.getLb();
        int wereExpectingTheAxle = param.getWereExpectingTheAxle();
        if(StringUtils.hasText(loomstate)){
            list = list.stream().filter(item -> loomstate.equals(item.getLoomstate())).collect(Collectors.toList());
        }
        if(lb>0){
            int day = lb == 1 ? 0 : lb == 2 ? 2 : lb == 3 ? 3 : 7;
            list = list.stream().filter(item -> {
                DateTime dt = DateUtil.parse(item.getLb());
                long between = Math.abs(dt.between(new Date(), DateUnit.DAY));
                return between <= day;
            }).collect(Collectors.toList());
        }
        if(wereExpectingTheAxle>0){
            int day = wereExpectingTheAxle == 1 ? 0 : wereExpectingTheAxle == 2 ? 2 : wereExpectingTheAxle == 3 ? 3 : 7;
            list = list.stream().filter(item -> {
                DateTime dt = DateUtil.parse(item.getWereExpectingTheAxle());
                long between = Math.abs(dt.between(new Date(), DateUnit.DAY));
                return between <= day;
            }).collect(Collectors.toList());
        }
        double min = 0;
        double max = 0;
        if(xl == 1){
            min = 95;
            max = 100;
        }
        if(xl == 2){
            min = 90;
            max = 95;
        }
        if(xl == 3){
            min = 85;
            max = 90;

        }
        if(xl == 4){
            min = 0;
            max = 85;

        }
        if(xl > 0){
            double finalMin = min;
            double finalMax = max;
            list = list.stream().filter(item -> {
                double v = NumberUtil.parseDouble(item.getXl(), 0.0);
                return v >= finalMin && v <= finalMax;
            }).collect(Collectors.toList());
        }

        return list;
    }

    public List<By01MaintenanceSchedule> wbList(JtQueryDto param) {
        // 添加分页支持
        Page.startPage();

        LambdaQueryWrapper<By01MaintenanceSchedule> wrapper = new LambdaQueryWrapper<>();
        // 只保留状态过滤条件，当传入"维保中"时只显示对应状态的数据
        String state = param.getState();
        String workshop = param.getWorkshop();
        String jth = param.getJth();
        String startDate = param.getStartDate();
        String endDate = param.getEndDate();
        wrapper.eq(StringUtils.hasText(state), By01MaintenanceSchedule::getOtherOrganiser1, state)
                .like(StringUtils.hasText(workshop), By01MaintenanceSchedule::getWorkshop, workshop)
                .like(StringUtils.hasText(jth), By01MaintenanceSchedule::getDeviceNamenumber, jth)
                .ge(StringUtils.hasText(startDate), By01MaintenanceSchedule::getVsDate, startDate)
                .le(StringUtils.hasText(endDate), By01MaintenanceSchedule::getVsDate, endDate)
                .orderByDesc(By01MaintenanceSchedule::getVsDate);
        List<By01MaintenanceSchedule> list = by01MaintenanceScheduleMapper.selectList(wrapper);
        LambdaQueryWrapper<ReplaceAccessories> replaceAccessoriesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        replaceAccessoriesLambdaQueryWrapper.eq(ReplaceAccessories::getType,0);
        List<ReplaceAccessories> replaceAccessories = replaceAccessoriesMapper.selectList(replaceAccessoriesLambdaQueryWrapper);
        // 获取维修人员的用工性质
        // 提取所有f896值（维修人员姓名），包括空值
        List<String> repairPersonnelNames = list.stream()
                .map(By01MaintenanceSchedule::getF896)
                .filter(Objects::nonNull) // 保留非null值
                // 移除空字符串过滤器以包含所有非null值
                .collect(Collectors.toList());

        // 查询对应的typeOfEmployment
        final Map<String, String> personnelTypeOfEmploymentMap = new HashMap<>();
        if (!repairPersonnelNames.isEmpty()) {
            // 从personnelManagementDataSheets表中查询typeOfEmployment
            LambdaQueryWrapper<PersonnelManagementDataSheets> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(PersonnelManagementDataSheets::getFe1e, repairPersonnelNames);
            List<PersonnelManagementDataSheets> personnelList = personnelManagementDataSheetsMapper.selectList(queryWrapper);

            // 构建姓名到用工性质的映射
            personnelList.forEach(personnel ->
                    personnelTypeOfEmploymentMap.put(
                            personnel.getFe1e(),
                            personnel.getPositions1()
                    )
            );
        }

        // 将typeOfEmployment设置到对应的By01MaintenanceSchedule对象中
        list.forEach(item -> {
            String repairPersonName = item.getF896();
            // 即使repairPersonName为空也进行处理
            item.setTypeOfEmployment(personnelTypeOfEmploymentMap.getOrDefault(repairPersonName, ""));
            item.setReplaceAccessoriesList(replaceAccessories.stream().filter(f -> f.getMaintenanceId().equals(item.getId())).collect(Collectors.toList()));
        });
        return list;
    }

    @Override
    public List<SchedulingOfSbbx01MalfunctionRep> gzList(JtQueryDto param) {
        // 添加分页支持
        Page.startPage();

        LambdaQueryWrapper<SchedulingOfSbbx01MalfunctionRep> wrapper = new LambdaQueryWrapper<>();
        // 只保留状态过滤条件，当传入"维保中"时只显示对应状态的数据
        String state = param.getState();
        String workshop = param.getWorkshop();
        String jth = param.getJth();
        String startDate = param.getStartDate();
        String endDate = param.getEndDate();
        String faultType = param.getFaultType();
        wrapper.eq(StringUtils.hasText(state), SchedulingOfSbbx01MalfunctionRep::getMaintenanceStatus, state)
                .like(StringUtils.hasText(workshop), SchedulingOfSbbx01MalfunctionRep::getWorkshop, workshop)
                .like(StringUtils.hasText(jth), SchedulingOfSbbx01MalfunctionRep::getDeviceNamenumber, jth)
                .like(StringUtils.hasText(faultType), SchedulingOfSbbx01MalfunctionRep::getFaultType, faultType)
                .ge(StringUtils.hasText(startDate), SchedulingOfSbbx01MalfunctionRep::getMaintenanceDate, startDate)
                .le(StringUtils.hasText(endDate), SchedulingOfSbbx01MalfunctionRep::getMaintenanceDate, endDate)
                .orderByDesc(SchedulingOfSbbx01MalfunctionRep::getId);
        List<SchedulingOfSbbx01MalfunctionRep> list = schedulingOfSbbx01MalfunctionRepMapper.selectList(wrapper);
        LambdaQueryWrapper<ReplaceAccessories> replaceAccessoriesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        replaceAccessoriesLambdaQueryWrapper.eq(ReplaceAccessories::getType,1);
        List<ReplaceAccessories> replaceAccessories = replaceAccessoriesMapper.selectList(replaceAccessoriesLambdaQueryWrapper);
        list.forEach(item->{
            String operator1 = item.getOperator();
            CorpMember corpMember = corpMemberMapper.selectById(operator1);
            item.setOperator(Objects.nonNull(corpMember) ? corpMember.getNick() : "");
            item.setReplaceAccessoriesList(replaceAccessories.stream().filter(f -> f.getMaintenanceId().equals(item.getId())).collect(Collectors.toList()));
        });

        // 获取维修人员的用工性质
        // 提取所有非空的f896值（维修人员姓名）
        List<String> repairPersonnelNames = list.stream()
                .map(SchedulingOfSbbx01MalfunctionRep::getFb02)
                .filter(Objects::nonNull)
                .filter(name -> !name.isEmpty())
                .collect(Collectors.toList());

        // 查询对应的typeOfEmployment
        final Map<String, String> personnelTypeOfEmploymentMap = new HashMap<>();
        if (!repairPersonnelNames.isEmpty()) {
            // 从personnelManagementDataSheets表中查询typeOfEmployment
            LambdaQueryWrapper<PersonnelManagementDataSheets> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(PersonnelManagementDataSheets::getFe1e, repairPersonnelNames);
            List<PersonnelManagementDataSheets> personnelList = personnelManagementDataSheetsMapper.selectList(queryWrapper);

            // 构建姓名到用工性质的映射
            personnelList.forEach(personnel ->
                    personnelTypeOfEmploymentMap.put(
                            personnel.getFe1e(),
                            personnel.getPositions1()
                    )
            );
        }

        // 将typeOfEmployment设置到对应的By01MaintenanceSchedule对象中
        list.forEach(item -> {
            String repairPersonName = item.getFb02();
            if (repairPersonName != null && !repairPersonName.isEmpty()) {
                item.setTypeOfEmployment(personnelTypeOfEmploymentMap.getOrDefault(repairPersonName, ""));
            }
        });
        return list;
    }





    /**
     * 添加或修改维保记录
     * @param body
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addWb(By01MaintenanceSchedule body) {
        CorpMember corpMember = getCorpMember();
        // 只设置必要的系统字段
        body.setOperator1(corpMember.getMemberId());
        body.setFb0f(LocalDateTime.now()); // 操作时间
        body.setTimeOfSubmission(new Date());
        body.setEndTime(DateUtil.date());
        body.setOtherOrganiser1(YWB); // 维保状态
        return addTempOrWb(body);
    }

    /**
     * 添加或修改故障记录
     * @param body
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addGz(SchedulingOfSbbx01MalfunctionRep body) {
        body.setOperationTime(DateUtil.date().toString());
        body.setTimeOfSubmission(new Date());
        body.setEndTime(DateUtil.date());
        body.setMaintenanceStatus(YWX); // 维保状态
        return addGzTempOrGz(body);
    }

    /**
     * 保存维保方法
     * @param body
     * @return
     */
    private boolean addTempOrWb(By01MaintenanceSchedule body) {
        boolean flag;
        body.setVsDate(LocalDate.now().toString());
        List<ReplaceAccessories> replaceAccessoriesList = body.getReplaceAccessoriesList();
        int total = replaceAccessoriesList.stream().mapToInt(ReplaceAccessories::getNumber).sum();
        body.setF0a6(total);
        if (Objects.isNull(body.getId())) {
            // 新增
            flag = by01MaintenanceScheduleMapper.insert(body) > 0;

            // 添加更换配件记录
            if (!replaceAccessoriesList.isEmpty()) {
                replaceAccessoriesList.forEach(item -> {
                    item.setMaintenanceId(body.getId());
                    item.setType(0);
                    item.setEndTime(new Date());
                });
                flag = replaceAccessoriesService.saveBatch(replaceAccessoriesList);
            }
        } else {
            By01MaintenanceSchedule one = by01MaintenanceScheduleMapper.selectById(body.getId());
            body.setOtherOrganiser(one.getOtherOrganiser());
            if(Objects.nonNull(body.getEndTime())) {
                long second = DateUtil.between(body.getOtherOrganiser(), body.getEndTime(), DateUnit.SECOND);
                body.setGuards(second);
            }
            // 修改
            flag = by01MaintenanceScheduleMapper.updateById(body) > 0;

            // 更新配件记录
            if (!replaceAccessoriesList.isEmpty()) {
                LambdaUpdateWrapper<ReplaceAccessories> raLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                raLambdaUpdateWrapper.eq(ReplaceAccessories::getMaintenanceId, body.getId());
                raLambdaUpdateWrapper.eq(ReplaceAccessories::getType, 0);

                // 删除旧配件记录
                replaceAccessoriesService.remove(raLambdaUpdateWrapper);

                // 添加新配件记录
                replaceAccessoriesList.forEach(item -> {
                    item.setMaintenanceId(body.getId());
                    item.setType(0);
                    item.setEndTime(new Date());
                });
                flag = replaceAccessoriesService.saveBatch(replaceAccessoriesList);
            }
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addWbTemp(By01MaintenanceSchedule body) {
        String deviceNamenumber = body.getDeviceNamenumber();
        if(StringUtils.hasText(deviceNamenumber)){
            List<String> stationNumberList = ReUtil.findAllGroup0(PatternPool.NUMBERS, deviceNamenumber);
            String stationNumber = stationNumberList.get(0);
            String equipment = deviceNamenumber.replace(stationNumber, "");
            body.setDeviceName(equipment);
            body.setStationNumber(stationNumber);
            body.setStationNumber1(stationNumber);
            body.setWorkshop(deviceNamenumber.contains("织布机") || deviceNamenumber.contains("空压机") ? "织布车间" : "准整车间");
        }
        body.setOtherOrganiser1(WBZ);
        body.setOtherOrganiser(DateUtil.date());
        body.setFb0f(LocalDateTime.now());
       return addTempOrWb(body);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addGzTemp(SchedulingOfSbbx01MalfunctionRep body) {
        String deviceNamenumber = body.getDeviceNamenumber();
        if(StringUtils.hasText(deviceNamenumber)){
            List<String> stationNumberList = ReUtil.findAllGroup0(PatternPool.NUMBERS, deviceNamenumber);
            String stationNumber = stationNumberList.get(0);
            String equipment = deviceNamenumber.replace(stationNumber, "");
            body.setDeviceInformation(equipment);
            body.setDeviceNumber(stationNumber);
            body.setWorkshop(deviceNamenumber.contains("织布机") || deviceNamenumber.contains("空压机") ? "织布车间" : "准整车间");
        }
        body.setMaintenanceStatus(WXZ);
        body.setOtherOrganiser(DateUtil.date());
        return addGzTempOrGz(body);

    }

    private boolean addGzTempOrGz(SchedulingOfSbbx01MalfunctionRep body){
        boolean flag;
        CorpMember corpMember = getCorpMember();
        // 设置系统字段
        body.setOperator(corpMember.getMemberId());
        body.setFb02(corpMember.getNick());
        body.setMaintenanceDate(LocalDate.now().toString());

        List<ReplaceAccessories> replaceAccessoriesList = body.getReplaceAccessoriesList();
        int total = replaceAccessoriesList.stream().mapToInt(ReplaceAccessories::getNumber).sum();
        body.setF6f1(total);
        if (body.getId() == null) {
            // 新增记录
            flag = schedulingOfSbbx01MalfunctionRepMapper.insert(body) > 0;

            // 处理更换配件
            if (flag && !body.getReplaceAccessoriesList().isEmpty()) {
                body.getReplaceAccessoriesList().forEach(item -> {
                    item.setMaintenanceId(body.getId());
                    item.setType(1); // 故障维修类型
                    item.setEndTime(new Date());
                });
                flag = replaceAccessoriesService.saveBatch(body.getReplaceAccessoriesList());
            }
        } else {
            SchedulingOfSbbx01MalfunctionRep one = schedulingOfSbbx01MalfunctionRepMapper.selectById(body.getId());
            body.setOtherOrganiser(one.getOtherOrganiser());
            if(Objects.nonNull(body.getEndTime())) {
                long second = DateUtil.between(body.getOtherOrganiser(), body.getEndTime(), DateUnit.SECOND);
                body.setTimeOut(second);
            }
            // 更新记录
            flag = schedulingOfSbbx01MalfunctionRepMapper.updateById(body) > 0;

            // 更新配件记录
            if (!body.getReplaceAccessoriesList().isEmpty()) {
                // 删除旧记录
                LambdaQueryWrapper<ReplaceAccessories> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(ReplaceAccessories::getMaintenanceId, body.getId())
                        .eq(ReplaceAccessories::getType, 1);
                replaceAccessoriesService.remove(wrapper);

                // 添加新记录
                body.getReplaceAccessoriesList().forEach(item -> {
                    item.setMaintenanceId(body.getId());
                    item.setType(1);
                    item.setEndTime(new Date());
                });
                flag = replaceAccessoriesService.saveBatch(body.getReplaceAccessoriesList());
            }
        }
        return flag;
    }


    private static final String WBZ = "维保中";
    private static final String WXZ = "维修中";
    private static final String YWB = "已完成";
    private static final String YWX = "已完成";

    @Override
    public By01MaintenanceSchedule getWb(String jth) {
        String now = LocalDate.now().toString();
        List<String> stationNumber = ReUtil.findAllGroup0(PatternPool.NUMBERS, jth);
        List<String> device = ReUtil.findAllGroup0(PatternPool.CHINESES, jth);
        if(stationNumber.isEmpty() || device.isEmpty()) return new By01MaintenanceSchedule();
        String equipment = device.get(0);
        String stationNumber1 = stationNumber.get(0);
        LambdaQueryWrapper<By01MaintenanceSchedule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(By01MaintenanceSchedule::getEquipment, equipment)
                .eq(By01MaintenanceSchedule::getStationNumber1, stationNumber1)
                .eq(By01MaintenanceSchedule::getVsDate, now)
                .eq(By01MaintenanceSchedule::getOtherOrganiser1,WBZ);
        By01MaintenanceSchedule by01MaintenanceSchedule = by01MaintenanceScheduleMapper.selectOne(wrapper);
        if(Objects.isNull(by01MaintenanceSchedule)){
            by01MaintenanceSchedule = new By01MaintenanceSchedule();
            by01MaintenanceSchedule.setOtherOrganiser(new Date());
            by01MaintenanceSchedule.setF896(getCorpMember().getNick());
            by01MaintenanceSchedule.setVsDate(now);
            by01MaintenanceSchedule.setOtherOrganiser1(WBZ);
            by01MaintenanceSchedule.setEquipment(equipment);
            by01MaintenanceSchedule.setStationNumber(stationNumber1);
            by01MaintenanceSchedule.setStationNumber1(stationNumber1);
            by01MaintenanceSchedule.setDeviceNamenumber(jth);
            by01MaintenanceSchedule.setWorkshop(stationNumber1.length() == 4 ? "织布车间" : "准整车间");
        }
        PersonnelManagementDataSheets personnelManagementDataSheets = personnelManagementDataSheetsService.getByLoginUserId();
        by01MaintenanceSchedule.setF896(personnelManagementDataSheets.getFe1e());
        return by01MaintenanceSchedule;
    }

    @Override
    public SchedulingOfSbbx01MalfunctionRep getGz(String jth) {
        String now = LocalDate.now().toString();
        List<String> stationNumber = ReUtil.findAllGroup0(PatternPool.NUMBERS, jth);
        List<String> device = ReUtil.findAllGroup0(PatternPool.CHINESES, jth);
        if(stationNumber.isEmpty() || device.isEmpty()) return new SchedulingOfSbbx01MalfunctionRep();
        String equipment = device.get(0);
        String stationNumber1 = stationNumber.get(0);
        LambdaQueryWrapper<SchedulingOfSbbx01MalfunctionRep> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchedulingOfSbbx01MalfunctionRep::getDeviceInformation, equipment)
                .eq(SchedulingOfSbbx01MalfunctionRep::getDeviceNumber, stationNumber1)
                .eq(SchedulingOfSbbx01MalfunctionRep::getMaintenanceDate, now)
                .eq(SchedulingOfSbbx01MalfunctionRep::getMaintenanceStatus,WXZ);
        SchedulingOfSbbx01MalfunctionRep schedulingOfSbbx01MalfunctionRep = schedulingOfSbbx01MalfunctionRepMapper.selectOne(wrapper);
        if(Objects.isNull(schedulingOfSbbx01MalfunctionRep)){
            schedulingOfSbbx01MalfunctionRep = new SchedulingOfSbbx01MalfunctionRep();
            schedulingOfSbbx01MalfunctionRep.setOtherOrganiser(new Date());
            schedulingOfSbbx01MalfunctionRep.setFb02(getCorpMember().getNick());
            schedulingOfSbbx01MalfunctionRep.setMaintenanceDate(now);
            schedulingOfSbbx01MalfunctionRep.setMaintenanceStatus(WXZ);
            schedulingOfSbbx01MalfunctionRep.setDeviceInformation(equipment);
            schedulingOfSbbx01MalfunctionRep.setDeviceNumber(stationNumber1);
            schedulingOfSbbx01MalfunctionRep.setDeviceNamenumber(jth);
            schedulingOfSbbx01MalfunctionRep.setWorkshop(stationNumber1.length() == 4 ? "织布车间" : "准整车间");
        }
        PersonnelManagementDataSheets personnelManagementDataSheets = personnelManagementDataSheetsService.getByLoginUserId();
        schedulingOfSbbx01MalfunctionRep.setFb02(personnelManagementDataSheets.getFe1e());
        return schedulingOfSbbx01MalfunctionRep;
    }

    @Override
    public Map<String,Object> wbtj(String startTime, String endTime, String workshop) {
        LambdaQueryWrapper<By01MaintenanceSchedule> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(By01MaintenanceSchedule::getVsDate, startTime, endTime);
        Map<String,Object> resultMap = new HashMap<>();
        // 添加车间ID参数
        List<WbTjVo> wbTjVoList = by01MaintenanceScheduleMapper.selectWbTjList(startTime, endTime, workshop);
        int totle = wbTjVoList.stream().mapToInt(WbTjVo::getF0a6).sum();
        int accessories = wbTjVoList.stream().mapToInt(WbTjVo::getAccessories).sum();
        int totalGuards = wbTjVoList.stream().mapToInt(WbTjVo::getGuards).sum();
        resultMap.put("wbAvgTime", DateUtil.formatBetween(totalGuards * 1000L, BetweenFormatter.Level.SECOND));//维保总平均长
        resultMap.put("wbCountAc", accessories);//维保配件总数
        resultMap.put("totle", totle);
        resultMap.put("startTime", startTime);
        resultMap.put("endTime", endTime);
        resultMap.put("wbTjVoList", wbTjVoList);//维保统计列表
        return resultMap;
    }

    @Override
    public Map<String,Object> gztj(String startTime, String endTime, String workshop) {
        Map<String,Object> resultMap = new HashMap();

        List<GzTjVo> wbTjVoList = schedulingOfSbbx01MalfunctionRepMapper.selectGzTjList(startTime, endTime, workshop);
        int totle = wbTjVoList.stream().mapToInt(GzTjVo::getF0a6).sum();
        int accessories = wbTjVoList.stream().mapToInt(GzTjVo::getAccessories).sum();
        int totalGuards = wbTjVoList.stream().mapToInt(GzTjVo::getGuards).sum();
        resultMap.put("wbAvgTime", DateUtil.formatBetween(totalGuards * 1000L, BetweenFormatter.Level.SECOND));//维保总平均长
        resultMap.put("wbCountAc", accessories);//维保配件总数
        resultMap.put("totle", totle);
        resultMap.put("startTime", startTime);
        resultMap.put("endTime", endTime);
        resultMap.put("wbTjVoList", wbTjVoList);//维保统计列表
        return resultMap;
    }

    /**
     * 维保详情记录
     * @param id
     * @return
     */
    @Override
    public WbInfoRecordVo wbinfoRecord(Integer id) {
        WbInfoRecordVo wbInfoRecordVo = by01MaintenanceScheduleMapper.selectWbInfoRecordVo(id);
        LambdaQueryWrapper<ReplaceAccessories> replaceAccessoriesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        replaceAccessoriesLambdaQueryWrapper.eq(ReplaceAccessories::getType,0).eq(ReplaceAccessories::getMaintenanceId,id);
        List<ReplaceAccessories> replaceAccessories = replaceAccessoriesMapper.selectList(replaceAccessoriesLambdaQueryWrapper);
        wbInfoRecordVo.setReplaceAccessoriesList(replaceAccessories);
        //处理图片
        return wbInfoRecordVo;
    }

    /**
     * 故障详情记录
     * @param id
     * @return
     */
    @Override
    public GzinfoRecordVo gzinfoRecord(Integer id) {
        GzinfoRecordVo gzInfoRecordVo = schedulingOfSbbx01MalfunctionRepMapper.selectGzinfoRecordVo(id);
        LambdaQueryWrapper<ReplaceAccessories> replaceAccessoriesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        replaceAccessoriesLambdaQueryWrapper.eq(ReplaceAccessories::getType,1).eq(ReplaceAccessories::getMaintenanceId,id);
        List<ReplaceAccessories> replaceAccessories = replaceAccessoriesMapper.selectList(replaceAccessoriesLambdaQueryWrapper);
        gzInfoRecordVo.setReplaceAccessoriesList(replaceAccessories);
        return gzInfoRecordVo;
    }

    private CorpMember getCorpMember(){
        IPersonnelManagementDataSheetsService personnel = SpringUtil.getBean(IPersonnelManagementDataSheetsService.class);
        return personnel.getCorpMemberByLogin();
    }

    @Override
    public List<EquipmentGroupDTO> getEquipmentByWorkshop(String workshop) {
        List<String> workshops = new ArrayList<>();
        workshops.add(workshop);
        return getEquipmentByWorkshops(workshops);
    }

    @Override
    public List<EquipmentGroupDTO> getEquipmentByWorkshops(List<String> workshops) {
        List<EquipmentGroupDTO> result = equipmentMapper.selectByWorkshops(workshops);
        List<String> device = result.stream().map(EquipmentGroupDTO::getDeviceName).distinct().collect(Collectors.toList());
        List<EquipmentGroupDTO> resultList = device.stream().map(d -> {
            EquipmentGroupDTO dto = new EquipmentGroupDTO();
            List<EquipmentGroupDTO> list = result.stream().filter(f -> f.getDeviceName().equals(d)).collect(Collectors.toList());
            dto.setDeviceName(list.get(0).getDeviceName());
            dto.setWorkshopBelongingTo(list.get(0).getWorkshopBelongingTo());
            dto.setStationNumber2(list.stream().map(EquipmentGroupDTO::getStationNumbersStr).collect(Collectors.toList()));
            return dto;
        }).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public Object pzkt() {
        Map<String,Object> map = baseMapper.selectPzktTop();
        List<Map<String,Object>> list = baseMapper.selectPzktList();
        map.put("tableList", list);
        return map;
    }

    @Override
    public Object pzktDetail(String noNo) {
        Map<String,Object> map = baseMapper.selectPzktDetail(noNo);
        return map;
    }

    /**
     * 获取故障类型列表
     *
     * @return
     */
    @Override
    public Object lzyc() {
        LambdaQueryWrapper<RundataInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNotNull(RundataInfo::getWarpbeam_ground_datetime);
        wrapper.orderByAsc(RundataInfo::getWarpbeam_ground_datetime);
        List<RundataInfo> list = rundataInfoService.list(wrapper);
        Map<String, List<RundataInfo>> map = new HashMap<>();
        List<RundataInfo> list12 = list.stream().filter(f -> {
            String warpbeamGroundDatetime = f.getWarpbeam_ground_datetime();
            DateTime endDate = DateUtil.parse(warpbeamGroundDatetime);
            DateTime beginDate = DateUtil.date();
            long between = DateUtil.between(beginDate, endDate, DateUnit.HOUR);
            return between <= 12;
        }).collect(Collectors.toList());
        List<RundataInfo> list24 = list.stream().filter(f -> {
            String warpbeamGroundDatetime = f.getWarpbeam_ground_datetime();
            DateTime endDate = DateUtil.parse(warpbeamGroundDatetime);
            DateTime beginDate = DateUtil.date();
            long between = DateUtil.between(beginDate, endDate, DateUnit.HOUR);
            return between <= 24;
        }).collect(Collectors.toList());
        map.put("listAll", list);
        map.put("list12", list12);
        map.put("list24", list24);
        return map;
    }
}
